package com.jluzh.provider;

import com.alibaba.fastjson.JSON;
import com.jluzh.anotation.FastJson;

import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

/**
 * @author EvanHuang
 * @date 11/5/2018 1:28 PM
 * @since
 */
@Provider
public class FastJsonBodyReader implements MessageBodyReader<Object>{
    @Override
    @Consumes(MediaType.APPLICATION_JSON)
    public boolean isReadable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
        return aClass.isAnnotationPresent(FastJson.class);
    }

    @Override
    public Object readFrom(Class<Object> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> multivaluedMap, InputStream inputStream) throws IOException, WebApplicationException {
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = bis.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        baos.flush();//7

        Object o = JSON.parseObject(baos.toByteArray(), type);//8
        System.out.println("providerReader...");
        return o;//9

    }
}
